#pragma once
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <memory>
#include <mutex>
#include <vector>
#include <queue>
#include <iostream>
#include "https_connection.h"

class HttpsConnectionPool : public std::enable_shared_from_this<HttpsConnectionPool> {
public:
    using Ptr = std::shared_ptr<HttpsConnectionPool>;
    using ResponseCallback = HttpsConnection::ResponseCallback;

    HttpsConnectionPool(boost::asio::io_context& ioc,
                        boost::asio::ssl::context& ssl_ctx,
                        const std::string& host,
                        const std::string& port,
                        size_t pool_size = 4);

    // 异步请求（自动轮询分配连接）
    void asyncSendRequest(const std::string& method,
                          const std::string& target,
                          const std::string& body,
                          const std::vector<std::pair<std::string,std::string>>& headers,
                          ResponseCallback callback);

    std::string syncSendRequest(const std::string& method,
                                         const std::string& target,
                                         const std::string& body,
                                         const std::vector<std::pair<std::string,std::string>>& headers);

private:
    std::shared_ptr<HttpsConnection> getAvailableConnection();
    void tryReconnect(std::shared_ptr<HttpsConnection> conn);

private:
    boost::asio::io_context& io_context_;
    boost::asio::ssl::context& ssl_context_;
    std::string host_;
    std::string port_;
    std::vector<std::shared_ptr<HttpsConnection>> connections_;
    std::queue<std::shared_ptr<HttpsConnection>> available_;
    std::mutex mutex_;
    size_t next_index_;
};
